package org.igeek.atomqq.activity;

import org.igeek.atomqq.AtomQQApplication;
import org.igeek.atomqq.R;
import org.igeek.atomqq.adapter.ChatsListAdapter;
import org.igeek.atomqq.adapter.FriendExpandListAdapter;
import org.igeek.atomqq.adapter.GroupListAdapter;
import org.igeek.atomqq.domain.Friend;
import org.igeek.atomqq.domain.FriendCategory;
import org.igeek.atomqq.domain.FriendInfo;
import org.igeek.atomqq.domain.Group;
import org.igeek.atomqq.domain.User;
import org.igeek.atomqq.net.Response;
import org.igeek.atomqq.service.AtomQQService;
import org.igeek.atomqq.service.MessageReceiver;
import org.igeek.atomqq.service.MessageReceiver.OnMessageRecevied;
import org.igeek.atomqq.task.FaceTask;
import org.igeek.atomqq.task.FaceTask.FaceResponse;
import org.igeek.atomqq.task.FriendInfoTask;
import org.igeek.atomqq.task.FriendListTask;
import org.igeek.atomqq.task.FriendListTask.FriendListResponse;
import org.igeek.atomqq.task.FriendOnlineTask;
import org.igeek.atomqq.task.FriendOnlineTask.FriendOnlineListResponse;
import org.igeek.atomqq.task.GroupListTask;
import org.igeek.atomqq.task.GroupListTask.GroupListResponse;
import org.igeek.atomqq.task.FriendSingleLongNickTask;
import org.igeek.atomqq.task.FriendSingleLongNickTask.LNickResponse;
import org.igeek.atomqq.task.MessagePoll;
import org.igeek.atomqq.task.TaskResultListener;
import org.igeek.atomqq.task.FriendInfoTask.FriendInfoResponse;
import org.igeek.atomqq.util.Utils;
import org.igeek.atomqq.vo.Chat;
import org.igeek.atomqq.vo.QQMessage;
import org.igeek.atomqq.vo.MsgChat;
import org.igeek.atomqq.vo.MsgFriend;
import org.igeek.atomqq.vo.MsgFriendListChange;
import org.igeek.atomqq.vo.MsgFriendStatus;
import org.igeek.atomqq.vo.MsgGroup;
import org.igeek.atomqq.vo.MsgSysGroup;
import org.igeek.atomqq.widget.AlwaysMarqueeTextView;
import org.igeek.atomqq.widget.FriendBadgeView;
import org.igeek.atomqq.widget.FriendCategoryView;
import org.igeek.atomqq.widget.FriendItemView;
import org.igeek.atomqq.widget.GroupBadgeView;
import org.igeek.atomqq.widget.GroupItemView;
import org.igeek.atomqq.widget.WorkSpace;

import android.app.Dialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SlidingDrawer;
import android.widget.TextView;

/** 
 * 程序主窗口 
 * @author <a href="http://hangxin1940.cnblogs.com">hangxin1940@gmail.com</a>
 * @time 2012-2-1 下午03:20:32 
 */
public class Main extends BaseActivity implements TaskResultListener,OnChildClickListener,OnItemLongClickListener,OnItemClickListener,OnMessageRecevied{
	
	
	
	private static final int FLAG_USERINFO=0x0;
	private static final int FLAG_LNICK=0x1;
	private static final int FLAG_FACE=0x2;
	private static final int FLAG_FRIENDLIST=0x3;
	private static final int FLAG_GROUPLIST=0x4;
	private static final int FLAG_FRIEND_ONLINE_LIST=0x5;
	
	
	
	private WorkSpace wsWorkspace;
	private ImageView ivUserFace;
	private AlwaysMarqueeTextView amtvUserLnick;
	private AlwaysMarqueeTextView amtvUserName;
	private LinearLayout sdllContent;
	private SlidingDrawer sdSlidingDrawer;
	private ImageView ivCurrentSpace;
	private ExpandableListView elvFriends;
	private ListView lvGroups;
	private LinearLayout llLoadingFriends;
	private LinearLayout llLoadingGroups;
	private ListView lvChats;
	
	private AtomQQApplication application;
	
	
	private FriendExpandListAdapter adapterFriends;
	private GroupListAdapter adapterGroups;
	private ChatsListAdapter adapterChats;
	
	
	
	//当前登录用户信息任务
	private FriendInfoTask taskFriendInfo;
	
	//当前登录用户个性签名任务
	private FriendSingleLongNickTask taskLNick;
	
	//当前登录用户头像任务
	private FaceTask taskFace;
	
	//好友列表任务
	private FriendListTask taskFriendList;
	
	//在线好友列表任务
	private FriendOnlineTask taskOnlineFriendList;
	
	//群列表任务
	private GroupListTask taskGroupList;
	
	
	private MessageReceiver messageReceiver;
	
	
	private User currentUser;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_main);
		
		wsWorkspace=(WorkSpace) findViewById(R.id.main_wsWorkspace);
		ivUserFace=(ImageView) findViewById(R.id.main_ivUserFace);
		amtvUserLnick=(AlwaysMarqueeTextView) findViewById(R.id.main_amtvUserLnick);
		amtvUserName=(AlwaysMarqueeTextView) findViewById(R.id.main_amtvUserName);
		sdllContent=(LinearLayout) findViewById(R.id.main_slidingDrawer_llContent);
		sdSlidingDrawer=(SlidingDrawer) findViewById(R.id.main_sdSlidingDrawer);
		ivCurrentSpace=(ImageView) findViewById(R.id.main_slidingDrawer_ivCurrentSpace);
		elvFriends=(ExpandableListView) findViewById(R.id.main_elvFriends);
		lvGroups=(ListView) findViewById(R.id.main_lvGroups);
		llLoadingFriends=(LinearLayout) findViewById(R.id.main_llLodingFriends);
		llLoadingGroups=(LinearLayout) findViewById(R.id.main_llLodingGroups);
		lvChats=(ListView) findViewById(R.id.main_slidingDrawer_lvChats);
		
		adapterFriends=new FriendExpandListAdapter(this);
		adapterGroups=new GroupListAdapter(this);
		adapterChats=new ChatsListAdapter(this);
		
		elvFriends.setAdapter(adapterFriends);
		elvFriends.setOnChildClickListener(this);
		elvFriends.setOnItemLongClickListener(this);
		elvFriends.setItemsCanFocus(true);
		
		lvGroups.setAdapter(adapterGroups);
		lvGroups.setOnItemClickListener(this);
		lvGroups.setOnItemLongClickListener(this);
		lvGroups.setItemsCanFocus(true);
		
		lvChats.setAdapter(adapterChats);
		lvChats.setOnItemClickListener(this);
		lvChats.setOnItemLongClickListener(this);
		lvChats.setItemsCanFocus(true);
		
		taskFriendInfo=new FriendInfoTask(this);
		taskLNick=new FriendSingleLongNickTask(this);
		taskFace=new FaceTask(this);
		taskFriendList=new FriendListTask(this);
		taskOnlineFriendList=new FriendOnlineTask(this);
		taskGroupList=new GroupListTask(this);
		
		taskFriendInfo.setOnTaskResult(this, FLAG_USERINFO);
		taskLNick.setOnTaskResult(this, FLAG_LNICK);
		taskFace.setOnTaskResult(this,FLAG_FACE);
		taskFriendList.setOnTaskResult(this, FLAG_FRIENDLIST);
		taskOnlineFriendList.setOnTaskResult(this, FLAG_FRIEND_ONLINE_LIST);
		taskGroupList.setOnTaskResult(this, FLAG_GROUPLIST);
		
		long uin=getIntent().getLongExtra("uin",-2);
		
		
		
		
		
		//首先获取application
		application=(AtomQQApplication) getApplication();
		
		messageReceiver =new MessageReceiver(this);
		
		
		//获得当前登录用户
		currentUser=application.getCurrentUser();
		
		
		//如果本地不存在当前用户信息，则从网络获取
		if(null==currentUser){
			amtvUserName.setText(Long.toString(uin));
			getCurrentUserInfo(uin);
			
			//获取好友列表
			taskFriendList.execute();
			//获取群列表
			taskGroupList.execute();
			
			String facePath=Utils.getFriendFacePath(uin, uin);
			
			if("".equals(facePath)){
				getCurrentUserFace(uin);
			}else if("sderr".equals(facePath)){
				
				ivUserFace.setImageResource(R.drawable.friendface);
			}else{
				ivUserFace.setImageURI(Uri.parse(facePath));
			}
		}else{
			String face=Utils.getFriendFacePath(currentUser.getUin(), currentUser.getUin());
			ivUserFace.setImageURI(Uri.parse(face));
			
			amtvUserName.setText(currentUser.getNick());
			amtvUserLnick.setText(currentUser.getLnick());
			
			adapterFriends.notifyDataSetChanged();
			llLoadingFriends.setVisibility(View.GONE);
			elvFriends.setVisibility(View.VISIBLE);
			adapterFriends.notifyDataSetChanged();
			
			llLoadingGroups.setVisibility(View.GONE);
			lvGroups.setVisibility(View.VISIBLE);
			adapterGroups.notifyDataSetChanged();
			adapterFriends.notifyDataSetChanged();
			
		}
		
	}
	
	
	@Override
	protected void onResume() {
		super.onResume();
		
		adapterFriends.notifyDataSetChanged();
		adapterGroups.notifyDataSetChanged();
		adapterChats.notifyDataSetChanged();
		
		IntentFilter broadCastFilter=new IntentFilter();
		broadCastFilter.addAction(MessagePoll.BROADCAST_MSG_FRIEND);
		broadCastFilter.addAction(MessagePoll.BROADCAST_MSG_FRIEND_LSTCHG);
		broadCastFilter.addAction(MessagePoll.BROADCAST_MSG_FRIEND_STATUS);
		broadCastFilter.addAction(MessagePoll.BROADCAST_MSG_GROUP);
		broadCastFilter.addAction(MessagePoll.BROADCAST_MSG_SYS_GROUP);
		broadCastFilter.setPriority(500);
		
		registerReceiver(messageReceiver, broadCastFilter, MessageReceiver.PERMISSION, null);
		
	}
	
	
	@Override
	protected void onPause() {
		super.onPause();
		
		unregisterReceiver(messageReceiver);
	}
	
	/**
	 * 刷新显示当前用户信息
	 */
	private void refreshSatatus(){
		amtvUserName.setText(currentUser.getNick());
		amtvUserLnick.setText(currentUser.getLnick());
	}
	
	
	/**
	 * 获取当前登录用户信息
	 */
	private void getCurrentUserInfo(long uin){
		
		taskFriendInfo.setParams(uin);
		taskFriendInfo.execute();
		
	}
	
	/**
	 * 获取当前登录用户签名
	 */
	private void getCurrentUserLNick(long uin){
		
		taskLNick.setParams(uin);
		taskLNick.execute();
		
	}
	
	/**
	 * 获取当前登录用户头像
	 */
	private void getCurrentUserFace(long uin){
		
		taskFace.setParams(uin,uin,FaceTask.FRIEND_FACE);
		taskFace.execute();
		
	}


	@Override
	public void onTaskResult(Response response, int flag) {
		if(null==response)
			return;
		
		switch (flag) {
		//获取到用户信息
		case FLAG_USERINFO:
			FriendInfo friendInfo=((FriendInfoResponse) response).getFriendInfo();
			
			User user=new User(friendInfo.getUin());
			
			user.setFriendInfo(friendInfo);
			
			application.setCurrentUser(user);
			
			currentUser=user;
			refreshSatatus();
			
			//获得个性签名
			getCurrentUserLNick(user.getUin());
			
			break;
		
		//获取到用户个性签名
		case FLAG_LNICK:
			Friend friend=((LNickResponse)response).getFriend();
			application.getCurrentUser().setLnick(friend.getLnick());
			refreshSatatus();
			break;
		
		//获取到用户头像
		case FLAG_FACE:
			Friend face=((FaceResponse)response).getFace();
			Drawable faceImg=Drawable.createFromPath(face.getFace());
			ivUserFace.setImageDrawable(faceImg);
			break;
		
		//获取到好友列表
		case FLAG_FRIENDLIST:
			application.setFriendCategores(((FriendListResponse)response).getCateogres());
			application.setFriends(((FriendListResponse)response).getFriends());
			adapterFriends.notifyDataSetChanged();
			llLoadingFriends.setVisibility(View.GONE);
			elvFriends.setVisibility(View.VISIBLE);
			
			//获取在线好友
			taskOnlineFriendList.execute();
			break;
			
		//获取在线好友
		case FLAG_FRIEND_ONLINE_LIST:
			application.setOnlineFriends(((FriendOnlineListResponse)response).getOnlineFriends());
			
			adapterFriends.notifyDataSetChanged();
			
			
			
			
			//开启消息轮询
			Intent service=new Intent(this,AtomQQService.class);
			startService(service);
			
			break;
			
		//获取群列表
		case FLAG_GROUPLIST:
			application.setGroups(((GroupListResponse)response).getGroups());
			llLoadingGroups.setVisibility(View.GONE);
			lvGroups.setVisibility(View.VISIBLE);
			adapterGroups.notifyDataSetChanged();
			break;
		}
		
	}
	
	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		switch (id) {
		case FriendSingleLongNickTask.ERROR:
			final Dialog dialogLongNickTimeOut= new Dialog(this,android.R.style.Theme_Translucent_NoTitleBar);
			
			dialogLongNickTimeOut.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialogLongNickTimeOut.setContentView(R.layout.dialog_message_singlebutton);
			((TextView)dialogLongNickTimeOut.findViewById(R.id.dialog_message_tvMessage)).setText("获取个性签名出错");
			Button lnickButton=(Button) dialogLongNickTimeOut.findViewById(R.id.dialog_message_btnButton);
			lnickButton.setText("重试");
			lnickButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dialogLongNickTimeOut.dismiss();
					taskLNick.execute();
					
				}
			});
			
			return dialogLongNickTimeOut;

		case FriendInfoTask.ERROR:
			final Dialog dialogInfoTimeOut= new Dialog(this,android.R.style.Theme_Translucent_NoTitleBar);
			
			dialogInfoTimeOut.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialogInfoTimeOut.setContentView(R.layout.dialog_message_singlebutton);
			((TextView)dialogInfoTimeOut.findViewById(R.id.dialog_message_tvMessage)).setText("获取账户信息出错");
			Button infoButton=(Button) dialogInfoTimeOut.findViewById(R.id.dialog_message_btnButton);
			infoButton.setText("重试");
			infoButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dialogInfoTimeOut.dismiss();
					taskFriendInfo.execute();
				}
			});
			
			return dialogInfoTimeOut;
		case FriendListTask.ERROR:
			final Dialog dialogListTimeOut= new Dialog(this,android.R.style.Theme_Translucent_NoTitleBar);
			
			dialogListTimeOut.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialogListTimeOut.setContentView(R.layout.dialog_message_singlebutton);
			((TextView)dialogListTimeOut.findViewById(R.id.dialog_message_tvMessage)).setText("获取好友列表出错");
			Button listButton=(Button) dialogListTimeOut.findViewById(R.id.dialog_message_btnButton);
			listButton.setText("重试");
			listButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dialogListTimeOut.dismiss();
					taskFriendList.execute();
				}
			});
			
			return dialogListTimeOut;
		case FriendOnlineTask.ERROR:
			final Dialog dialogOnlineTimeOut= new Dialog(this,android.R.style.Theme_Translucent_NoTitleBar);
			
			dialogOnlineTimeOut.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialogOnlineTimeOut.setContentView(R.layout.dialog_message_singlebutton);
			((TextView)dialogOnlineTimeOut.findViewById(R.id.dialog_message_tvMessage)).setText("获取在线好友出错");
			Button onlineButton=(Button) dialogOnlineTimeOut.findViewById(R.id.dialog_message_btnButton);
			onlineButton.setText("重试");
			onlineButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dialogOnlineTimeOut.dismiss();
					taskOnlineFriendList.execute();
				}
			});
			
			return dialogOnlineTimeOut;
		}
		return super.onCreateDialog(id, args);
	}


	@Override
	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long id) {
		
		long uin=application.getFriendCategory(groupPosition).getFriend(childPosition).getUin();
		
		Intent intent=new Intent(this,CommonChat.class);
		Bundle bund=new Bundle();
		bund.putInt(CommonChat.TYPE, Chat.FRIEND);
		bund.putLong(CommonChat.UIN, uin);
		intent.putExtras(bund);
		startActivity(intent);
		
		return false;
	}


	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
			
		if(parent==elvFriends){
		
			String className=view.getClass().getName();
			
			//如果是好友分组
			if(className.equals(FriendCategoryView.class.getName())){
				FriendCategory category=((FriendCategoryView)view).getCategory();
				
				
			}
			
			//如果是好友
			else if(className.equals(FriendItemView.class.getName())){
				FriendItemView friendView=(FriendItemView)view;
				Friend friend=friendView.getFriend();
				FriendBadgeView badgeV=new FriendBadgeView(this, friend);
				try {
					Utils.showViewOnTopWindow(friendView.getBadgeView(),badgeV.getCustomHeight() ,badgeV, this);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}else{
			GroupItemView groupView=(GroupItemView) view;
			Group group=groupView.getGroup();
			GroupBadgeView badgeV=new GroupBadgeView(this, group);
			
			try {
				Utils.showViewOnTopWindow(groupView.getBadgeView(),badgeV.getCustomHeight() ,badgeV, this);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return true;
	}


	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if(parent==lvChats){
			Chat chat=application.getChat(position).get(0);
			int type=chat.getType();
			
			Intent intent=new Intent(this,CommonChat.class);
			Bundle bund=new Bundle();
			if(type==Chat.FRIEND){
				bund.putInt(CommonChat.TYPE, Chat.FRIEND);
				bund.putLong(CommonChat.UIN, chat.getUin());
			}else{
				bund.putInt(CommonChat.TYPE, Chat.GROUP);
				bund.putLong(CommonChat.UIN, chat.getGcode());
			}
			intent.putExtras(bund);
			startActivity(intent);
		}else if(parent==lvGroups){
			long uin=application.getGroup(position).getCode();
			
			Intent intent=new Intent(this,CommonChat.class);
			Bundle bund=new Bundle();
			bund.putInt(CommonChat.TYPE, Chat.GROUP);
			bund.putLong(CommonChat.UIN, uin);
			intent.putExtras(bund);
			startActivity(intent);
		}
		
		
		
	}


	
	/**
	 * 处理消息接受
	 */
	@Override
	public void handleMessage(int type,QQMessage message) {
		switch (type) {
		case MessageReceiver.BROADCAST_TYPE_FRIEND:
			
			adapterFriends.notifyDataSetChanged();
			adapterChats.notifyDataSetChanged();
			
			break;

		case MessageReceiver.BROADCAST_TYPE_FRIEND_LISTCHG:
			
			adapterFriends.notifyDataSetChanged();
			
			break;
			
		case MessageReceiver.BROADCAST_TYPE_FRIEND_STATUS:
			
			adapterFriends.notifyDataSetChanged();
			
			break;
			
		case MessageReceiver.BROADCAST_TYPE_GROUP:
			
			adapterGroups.notifyDataSetChanged();
			adapterChats.notifyDataSetChanged();
			
			
			break;
			
		case MessageReceiver.BROADCAST_TYPE_SYS_GROUP:
			
		
			
			
			break;

		}
		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (event.getKeyCode()) {
		case KeyEvent.KEYCODE_BACK:
			if(sdSlidingDrawer.isOpened()){
				sdSlidingDrawer.animateClose();
				return false;
			}

		}
		
		return true;
	}
	
}
